package com.deyuanyun.pic.ctrl.service.pushmsg;

import com.deyuanyun.pic.common.spring.SpringAppliction;
import com.deyuanyun.pic.common.util.CommonUtil;
import com.deyuanyun.pic.common.util.StringUtils;
import com.deyuanyun.pic.ctrl.domain.EqptCptestStation;
import com.deyuanyun.pic.ctrl.enumeration.CathodicProtectionEvaluationEnum;
import com.deyuanyun.pic.ctrl.enumeration.TestStationFineStatusEnum;
import com.deyuanyun.pic.ctrl.excelImport.PicCtrlExinspCptestStationExcel;
import com.deyuanyun.pic.ctrl.mapper.EqptCptestStationMapper;
import com.deyuanyun.pic.settings.controller.dto.BizMsgThresholdVO;
import com.deyuanyun.pic.settings.domain.base.BizMsgUser;
import com.deyuanyun.pic.settings.enumeration.ThresholdType;
import com.deyuanyun.pic.settings.service.msgtemplate.AbstractPushMsgTemplate;
import com.deyuanyun.pic.settings.service.msgtemplate.MsgQueue;
import com.deyuanyun.pic.settings.support.utils.PipeDictUtils;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 *  腐蚀控制---测试桩检测数据录入消息推送
 *  @author axiao(xj08.dream@gmail.com)
 *  @date 2016-10-21
 *  @version 1.0
 *  Histroy: [修改人][时间][描述]
 */
public class ExinspCptestStationPushMsg extends AbstractPushMsgTemplate {

    private static final Logger LOGGER = LoggerFactory.getLogger(ExinspCptestStationPushMsg.class);

    private String createReamrk; //创建备注

    @Override
    public void doPushMsgData() {
        if(super.interfaceParam.isEmpty()) {
            LOGGER.info("没有传入参数");
            return;
        }
        Object obj = super.interfaceParam.get(CtrlPushMsgCons.LIST_KEY);
        if(obj != null && (obj instanceof List)) {
            EqptCptestStationMapper eqptCptestStationMapper = SpringAppliction.getBean(EqptCptestStationMapper.class);
            BizMsgThresholdVO cathodicProtection = super.bizMsgThresholdService.queryDataByTypeOne(ThresholdType.INTERNAL_CATHODIC_PROTECTION_INPUT.getValue());
            BizMsgThresholdVO potential = super.bizMsgThresholdService.queryDataByTypeOne(ThresholdType.INTERNAL_POTENTIAL_INPUT.getValue());
            if(cathodicProtection == null || potential == null) {
                LOGGER.info("没有查询到阀值信息");
                return;
            }
            Object cathodicProtectionObj = cathodicProtection.getThresholdContentJson();
            Object potentialObj = potential.getThresholdContentJson();
            if(cathodicProtectionObj == null || cathodicProtectionObj == "" || !(cathodicProtectionObj instanceof Map) ||
                    potentialObj == null || potentialObj == "" || !(potentialObj instanceof Map)) {
                LOGGER.info("没有设置对应的字段值或者不是map结构");
                return;
            }
            Map cathodicProtectionMap = (Map) cathodicProtectionObj;
            Map potentialMap = (Map)potentialObj;

            Object overProtectionObj = cathodicProtectionMap.get("overProtection");
            Object underProtectionObj = cathodicProtectionMap.get("underProtection");
            boolean isOverProtection = false, isUnderProtection = false; //过保护和欠保护
            if(overProtectionObj != null && !"".equals(overProtectionObj)) //业务阀值中设置的“过保护”值
                isOverProtection = true;
            if(underProtectionObj != null && !"".equals(underProtectionObj)) //业务阀值中设置的“欠保护”值
                isUnderProtection = true;

            Object damageAvailObj = potentialMap.get("damageAvail");
            Object damageNotAvailObj = potentialMap.get("damageNotAvail");
            Object deficiencyObj = potentialMap.get("deficiency");

            boolean isDamageAvail = false, isDamageNotAvail = false, isDeficiency = false ;//损伤可用、损伤不可用和缺失

            if(damageAvailObj != null && !"".equals(damageAvailObj)) //业务阀值中设置的“损伤可用”值
                isDamageAvail = true;
            if(damageNotAvailObj != null && !"".equals(damageNotAvailObj)) //业务阀值中设置的“损伤不可用”值
                isDamageNotAvail = true;
            if(deficiencyObj != null && !"".equals(deficiencyObj)) //业务阀值中设置的“缺失”值
                isDeficiency = true;

            List<PicCtrlExinspCptestStationExcel> list = (List<PicCtrlExinspCptestStationExcel>) obj;

            for (int i = 0; i < list.size(); i++) {
                PicCtrlExinspCptestStationExcel stationExcel = list.get(i);
                String protectingState = stationExcel.getProtectingState();
                if(StringUtils.isNotEmpty(protectingState)) {
                    //测试桩检测数据---阴保有效性评价判断，消息推送
                    String protectingStateStr = "";
                    if(CathodicProtectionEvaluationEnum.EXCESSIVE.toString().equals(protectingState) && isOverProtection) { //过保护
                        protectingStateStr = CathodicProtectionEvaluationEnum.EXCESSIVE.getLabel();
                    }
                    if(CathodicProtectionEvaluationEnum.DEFICIENCY.toString().equals(protectingState) && isUnderProtection) {//欠保护
                        protectingStateStr = CathodicProtectionEvaluationEnum.DEFICIENCY.getLabel();
                    }
                    String pipeLineId = stationExcel.getPipeLineId();
                    String pipeLineName = PipeDictUtils.getLineById(pipeLineId).getName();
                    EqptCptestStation eqptCptestStation = eqptCptestStationMapper.selectByPrimaryKey(stationExcel.getTestStationId());
                    if (eqptCptestStation == null) {
                        continue;
                    }
                    String customNumber = eqptCptestStation.getCustomNumber();
                    if(StringUtils.isNotEmpty(protectingStateStr)) {
                        super.thresListCastString(Lists.newArrayList(pipeLineName, customNumber, protectingStateStr));
                        this.createReamrk = "阴极保护有效性评价结果录入消息推送";
                        initializeBizMsgSends(cathodicProtection);
                    }

                    //测试桩检测数据---电位桩完好情况判断，消息推送
                    String testStationFineStatus = stationExcel.getTestStationFineStatus();
                    String testStationStr = "";

                    if(TestStationFineStatusEnum.FAILURE_USABLE.toString().equals(testStationFineStatus) && isDamageAvail) { //损伤可用
                        testStationStr = TestStationFineStatusEnum.FAILURE_USABLE.getLabel();
                    }
                    if(TestStationFineStatusEnum.FAILURE.toString().equals(testStationFineStatus) && isDamageNotAvail) { //损伤不可用
                        testStationStr = TestStationFineStatusEnum.FAILURE.getLabel();
                    }
                    if(TestStationFineStatusEnum.LACK.toString().equals(testStationFineStatus) && isDeficiency) { //缺失
                        testStationStr = TestStationFineStatusEnum.LACK.getLabel();
                    }
                    if(StringUtils.isNotEmpty(testStationStr)){
                        super.thresListCastString(Lists.newArrayList(pipeLineName, customNumber, testStationStr));
                        this.createReamrk = "电位桩完好结果录入消息推送";
                        initializeBizMsgSends(potential);
                    }
                }
            }
        }
    }

    /**
     * @param args 参数说明：
     * <pre>
     * arg[0]：为业务阀值实体信息，类型为：{@link BizMsgThresholdVO}<br />
     * </pre>
     */
    @Override
    public void initializeBizMsgSends(Object... args) {
        BizMsgThresholdVO msgThresholdVO = (BizMsgThresholdVO) args[0];
        super.roleList = msgThresholdVO.getRoleIdList();
        String msgContent = msgThresholdVO.getMsgContent();

        if (super.roleList != null && !super.roleList.isEmpty()) {
            Set<String> userIds = super.bizMsgThresholdService.queryUseIdByRoleIds(super.roleList); //用户id集合
            List<MsgQueue.BizMsgUserInfo> userInfos = new ArrayList<MsgQueue.BizMsgUserInfo>();
            for (String userId : userIds) {
                BizMsgUser bizMsgUser = new BizMsgUser();
                bizMsgUser.setCreateRemark(this.createReamrk);
                bizMsgUser.setCreateDate(new Date());
                if (StringUtils.isNotEmpty(msgContent))//消息内容不为空的时候设置到消息推送实体类
                    bizMsgUser.setMsgContent(msgContent);
                if (StringUtils.isNotEmpty(super.thresholdContent)) { //设置阀值内容
                    bizMsgUser.setThresholdContent(super.thresholdContent);
                }
                bizMsgUser.setUserId(userId);
                bizMsgUser.setId(CommonUtil.getUUID());

                userInfos.add(msgQueue.new BizMsgUserInfo().setValid(false).setBizMsgUser(bizMsgUser));
            }
            if(!userInfos.isEmpty()) {
                //封装好需要发送的消息信息交给队列来推送消息
                MsgQueue.MsgInfo msgInfo = msgQueue.new MsgInfo().setBizMsgThresholdId(msgThresholdVO.getId())
                        .setThresholdSet(msgThresholdVO.getThresholdContent()).setRoleIds(super.roleList);
                msgQueue.addOperator(msgQueue.new PushMsgOperator(userInfos, msgInfo));
            }
        }
        super.roleList = null;
    }

    @Override
    public boolean valiIsPush(Map<String, Object> valiMap) {
        return false;
    }
}
